import Vue from 'vue'
import Main from './index.vue'
let ToastConstructor = Vue.extend(Main)

let instance
let instances = []
let seed = 1

const Toast = function (options) {
  if (Vue.prototype.$isServer) return
  options = options || {}
  if (typeof options === 'string') {
    options = {
      message: options
    }
  }
  let userOnClose = options.onClose
  let id = 'toast_' + seed++
  options.onClose = function () {
    Toast.close(id, userOnClose)
  }
  instance = new ToastConstructor({
    data: options
  })
  instance.id = id
  instance.$mount()
  document.body.appendChild(instance.$el)
  instance.visible = true
  instances.push(instance)
  return instance
}

Toast.close = function(id, userOnClose) {
  let len = instances.length
  let index = -1
  for (let i = 0; i < len; i++) {
    if (id === instances[i].id) {
      index = i
      if (typeof userOnClose === 'function') {
        userOnClose(instances[i])
      }
      instances.splice(i, 1)
      break
    }
  }
  if (len <= 1 || index === -1 || index > instances.length - 1) return
}

Toast.closeAll = function() {
  for (let i = instances.length - 1; i >= 0; i--) {
    instances[i].close()
  }
}

export default Toast
